package cn.le.InternalClass;

import cn.le.InternalClass.inter.Incrementable;

/**
 * Created by admin on 2017/4/24.
 *闭包是一个可调用的对象,它记录了一些信息,这些信息来自创建它的作用预,用过这个定义,可以看出内部类是面向对象
 * 的闭包,因为它不仅外围类对象(创建内部类的作用域)的信息,还自动拥有一个指向此外围对象的引用,
 * 在此作用域内,内部类有权操作所有的成员,包括private成员
 *
 *
 */
public class Callee1 implements Incrementable {

    private int i = 0;
    
    public void increment() {
        i++;
        System.out.println(i);
    }
}

class MyIncrement{
    public void increment()
    {
        System.out.println("Other operation");
    }
    static void f(MyIncrement mi)
    {
        mi.increment();
    }
}
class Callee2 extends  MyIncrement
{
    private  int i = 0;
    public void incrment()
    {
        super.increment();
        i++;
        System.out.println(i);
    }
    private class Closure implements  Incrementable{
        public void increment()
        {
            Callee2.this.incrment();
        }
    }
    Incrementable getCallbackRefference()
    {
        return new Closure();
    }
}
class Caller{

    private Incrementable callbackReference;
    Caller(Incrementable cbh)
    {
        callbackReference = cbh;
    }
    void go()
    {
        callbackReference.increment();
    }
}
class Callbacks{
    public static void main(String[] args) {
        Callee1 c1 = new Callee1();
        Callee2 c2 = new Callee2();

        MyIncrement.f(c2);

        Caller caller1 = new Caller(c1);
        Caller caller2 = new Caller(c2.getCallbackRefference());

        caller1.go();
        caller1.go();
        caller2.go();
        caller2.go();
    }
}